<template>
  <a-drawer
    title="收支账户信息"
    :visible="visible"
    :destroyOnClose="true"
    :width="800"
    :body-style="{
      height: 'calc(100% - 55px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
    @close="handleClose"
  >
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: 'max-content' }"
    >
      <template #title>
        <div class="flex justify-between header-clue">
          <div class="flex-1">
            <a-form layout="vertical">
              <a-row :gutter="8">
                <a-col :span="4">
                  <a-form-item>
                    <a-input
                      placeHolder="请输入条目名称"
                      v-model:value="searchParams.name"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item>
                    <a-input
                      placeHolder="请输入银行账户"
                      v-model:value="searchParams.bank"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item>
                    <a-select
                      style="width: 100%"
                      :allowClear="true"
                      placeholder="请选择状态"
                      v-model:value="searchParams.status"
                      :options="statusOptions"
                    />
                  </a-form-item>
                </a-col>

                <a-col :span="4">
                  <a-form-item label="">
                    <a-space>
                      <a-button type="primary" @click="getTableData(true)">
                        搜索
                      </a-button>
                      <a-button @click="reset">重置</a-button>
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </div>
        </div>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'status'">
          <a-switch
            v-permission="['manageAccount', 'curd', 'status']"
            :checkedValue="1"
            :unCheckedValue="0"
            :checked="text"
            checked-children="开启"
            un-checked-children="关闭"
            @click="(checked) => handleStatusClick(record.id, checked)"
          />
        </template>
        <template v-if="column.key === 'action'">
          <a-button
            type="link"
            v-permission="['manageAccount', 'curd', 'edit']"
            @click="editAccount(text)"
          >编辑</a-button
          >
          <a-button
            type="link"
            v-permission="['manageAccount', 'curd', 'delete']"
            danger
            @click="deleteAccount(text)"
          >删除</a-button
          >
        </template>
      </template>
    </a-table>

    <AccountAdd
      @cancel="editAccountClose"
      @success="editSuccess"
      :visible="editVisible"
      :id="currentId"
      @request="$utils.commonRequest"
    />
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  onActivated,
  reactive,
  toRefs,
} from "vue";

import { useRouter, useRoute } from "vue-router";
import request from "@/common/utils/request";
import {Form, message} from "ant-design-vue";
import utils from "@/common/utils/utils";
const useForm = Form.useForm;
import AccountAdd from "@/views/setting/UserAccount/modules/AccountAdd.vue";
export default defineComponent({
  name: "AccountList",
  components: {
    AccountAdd,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  setup(props, { emit }) {
    const $router = useRouter();

    const state = reactive({
      dataList: [],
      loading: false,
      total: 0,
      page: 1,
      pageSize: 10,
      currentId: 0,
      editVisible: false,
    });

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const searchParams = reactive({
      name: "",
      bank: "",
      status: undefined,
    });
    const { resetFields } = useForm(searchParams, {});

    const getTableData = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
      }
      const params = {
        page: state.page,
        pageSize: state.pageSize,
        org_branch_id: props.id,
      };
      for (let key in searchParams) {
        if (searchParams[key] || searchParams[key] === 0) {
          params[key] = searchParams[key];
        }
      }
      request.get("/org", "/manage/account", params)
        .then((res) => {
          state.dataList = res.list;
          state.total = Number(res.total);
        })
        .finally(() => {
          state.loading = false;
        });
    };

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getTableData();
    };

    const reset = () => {
      resetFields();
      getTableData(true);
    };

    const handleClose = () => {
      emit('handleCancel');
    };

    const handleStatusClick = (id, checked) => {
      request.put("/org", "/manage/account/status", {
        id,
        status: checked,
      }).then((res) => {
        message.success(res.msg || "修改成功");
        getTableData();
      });
    };

    const editAccount = (id) => {
      state.currentId = id || 0;
      state.editVisible = true;
    };

    const editAccountClose = () => {
      state.editVisible = false;
    };

    const deleteAccount = (id) => {
      utils.modalConfirm({
        content: "确认要删除当前账户配置吗？",
        okType: "danger",
        centered: true,
        onOk: () => {
          request.del("/org", "/manage/account", { id, needMsg: true }).then((res) => {
            message.success(res.msg || "删除成功");
            getTableData();
            emit('refreshData');
          });
        },
      });
    };

    const editSuccess = () => {
      editAccountClose();
      getTableData();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getTableData(true)
        } else {
          resetFields();
          state.dataList = [];
          state.loading = false;
          state.total = 0;
          state.page = 1;
          state.pageSize = 10;
        }
      }
    );

    return {
      ...toRefs(state),
      columns,
      pagination,
      statusOptions,
      searchParams,
      handleClose,
      getTableData,
      handleTableChange,
      reset,
      handleStatusClick,
      editAccount,
      editAccountClose,
      deleteAccount,
      editSuccess,
    };
  },
});

const columns = [
  {
    title: "条目名称",
    dataIndex: "name",
    key: "name",
    width: "16%",
  },
  {
    title: "收款公司",
    dataIndex: "company",
    key: "company",
    width: "17%",
    customRender: ({ text, record, index }) => {
      return record?.company ? record?.company : record?.new_company_name || '--';
    },
  },
  {
    title: "开户银行",
    dataIndex: "bank",
    key: "bank",
    width: "17%",
  },
  {
    title: "银行账号",
    dataIndex: "bank_account",
    key: "bank_account",
    width: "20%",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 100,
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: 180,
  },
];

const statusOptions = [
  {
    label: '全部',
    value: 2,
  },
  {
    label: '正常',
    value: 1,
  },
  {
    label: '禁用',
    value: 0,
  },
]
</script>

<style lang="less" scoped>

</style>
